#!/usr/bin/python
# -*- coding: utf8 -*-

import os, sys
import signal
import time
from threading import Thread, Event
# from typing import Optional

import pyautogui as gui
from termcolor import colored

import auto_gaming_utils as utils

# 钓鱼数量
FISH_COUNT = 0

def strike(key = "space"):
    gui.press(key)

def do_fish():

    img_fishing = utils.ImgElement("fishing", "fishing.png", 1030, 555, 116, 120)
    img_fish_with_fish = utils.create_img_element_by_points("fishing", "fish_with_fish.png", 1155, 649, 1243, 741)
    text_fish_success = utils.ImgElement("fishing", "catched.png", 590, 230, 97, 33)

    # ag.screenshot("z:\\a.png", region=result_region)

    is_fish_with_fish = False # 触发了“授鱼以鱼”
    global FISH_COUNT
    while utils.GAME_WINDOW.isActive:

        # 开始钓鱼
        print("开始钓鱼")
        if is_fish_with_fish:
            is_fish_with_fish = False
            strike("e")
        else:
            strike()
        time.sleep(1.5)

        # 等待阶段
        head_printed = False
        while img_fishing.matched():
            if head_printed:
                print('.', end='', flush=True)
            else:
                print('等鱼上钩', end='', flush=True)
                head_printed = True
            time.sleep(1)
        
        # 收杆阶段
        strike()
        time.sleep(3.5)

        while text_fish_success.matched():
            FISH_COUNT = FISH_COUNT + 1
            print(colored(f"{os.linesep}钓到鱼了！ 总数：{FISH_COUNT}", "green", attrs=["bold"]))
            time.sleep(1.5)
            strike()
            time.sleep(2)
            # break

        # 处理“授鱼以鱼”
        if img_fish_with_fish.matched():
            print(colored("触发了“授鱼以鱼”", "yellow", attrs=["bold"]))
            FISH_COUNT = FISH_COUNT - 1
            is_fish_with_fish = True

if __name__ == "__main__":

    gui.FAILSAFE = True  # 安全模式：当鼠标移动到屏幕左上角时自动中止程序  默认为True，强烈建议保持启用
    gui.PAUSE = 0.1  # 所有PyAutoGUI函数之间的默认暂停时间（秒）  可调整以模拟不同的操作速度
    gui.FAILSAFE_POINTS = [(0, 0), (1, 0), (0, 1), (1, 1)] # 自动中止的安全区域坐标点 默认值

    # 在特定窗口内执行操作
    if not utils.fetch_game_window():
        print(colored("没有获取到游戏窗口!", "red", attrs=['bold']))
        sys.exit(1)

    print("设置窗口大小为：1280 x 720")
    utils.resize_win_to_correct_size()
    print("移动窗口至左下角")
    utils.move_win_to_left_bottom()

    while not utils.GAME_WINDOW.isActive:
        print("等待窗口被激活。")
        time.sleep(2)
    # ag.press('alt')
    # win_game.activate()
    
    thread_fish = Thread(target=do_fish)
    thread_fish.daemon = True
    thread_fish.start()

    event_quit = Event() # 退出事件，用以处理用户的退出请求
    
    signal.signal(signal.SIGINT, lambda s, f: event_quit.set() )

    while not event_quit.is_set() and utils.GAME_WINDOW.isActive:
        time.sleep(2)
